package proxy.util;

import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.RequestLine;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.message.BasicRequestLine;

public class RequestUtil {
	
	public static HttpHost getHttpHost(HttpRequest request){
		//Header header = request.getFirstHeader("Host");
		String uri = null;
		String remoteHost = "";
		int remotePort = 80;
		int position = -1;
		
		uri = request.getRequestLine().getUri();
		position = uri.indexOf("://");
		if (position != -1){
			remoteHost = uri.substring(position + 3);
		}else{
			remoteHost = uri;
		}
		position = remoteHost.indexOf("/");
		if (position != -1){
			remoteHost = remoteHost.substring(0, position);
		}
		position = remoteHost.indexOf(":");
		if (position != -1){
			String hostname = remoteHost;
			remoteHost = remoteHost.substring(0, position);
			try{
				remotePort = Integer.parseInt(hostname.substring(position + 1));
			}catch (NumberFormatException e) {
				e.printStackTrace();
			}
		}
		return new HttpHost(remoteHost, remotePort, "CONNECT".equalsIgnoreCase(request.getRequestLine().getMethod()) ? "https" : "http");
	}
	
	public static HttpRequest convertRequest(HttpRequest request, boolean hasEntity){
		HttpRequest ret = null;
		RequestLine requestLine = new BasicRequestLine(request.getRequestLine().getMethod(), getUriWithoutHost(request.getRequestLine().getUri()), request.getProtocolVersion());
		if (hasEntity){
			HttpEntityEnclosingRequest entityEnclosingRequest = new BasicHttpEntityEnclosingRequest(requestLine);
			entityEnclosingRequest.setEntity(((HttpEntityEnclosingRequest)request).getEntity());
			ret = entityEnclosingRequest;
		}else{
			ret = new BasicHttpRequest(requestLine);
		}
		ret.setHeaders(request.getAllHeaders());
		return ret;
	}
	
	private static String getUriWithoutHost(String uri){
		int position = uri.indexOf("://");
		if (position != -1){
			uri = uri.substring(position + 3);
		}
		position = uri.indexOf("/");
		if (position != -1){
			uri = uri.substring(position);
		}else{
			uri = "/";
		}
		return uri;
	}
}
